package com.wocao.admin.business;

import com.wocao.commom.constant.CommonConstant;
import com.wocao.commom.utils.BeanCopyUtil;
import com.wocao.commom.utils.CommonUtil;
import com.wocao.system.entity.SysUserDo;
import com.wocao.system.entity.vo.user.SysUserAddVo;
import com.wocao.system.entity.vo.user.SysUserVo;
import com.wocao.system.service.SysUserRoleService;
import com.wocao.system.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;

/**
 * 〈功能详细描述〉
 *
 * @author sunhao
 * @date 2021/8/13
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class SysUserBusiness {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 功能描述: 根据用户账号查询用户信息<br>
     *
     * @param userName 用户账号
     * @return com.dpl.iot.admin.entity.SysUserVo
     * @author eggg 2021/8/14 9:21
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本]（可选）
     */
    public SysUserVo getSysUserByUserName(String userName) {
        SysUserDo sysUserDo = sysUserService.getSysUserByUserName(userName);
        return BeanCopyUtil.copyObj(sysUserDo, SysUserVo.class);
    }

    /**
     * 功能描述: 添加用户信息<br>
     *
     * @param sysUserAddVo 用户添加实体
     * @author 翟思权 2021-08-27 15:55
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本]（可选）
     */
    public void addUser(SysUserAddVo sysUserAddVo) {
        SysUserDo sysUserDo = BeanCopyUtil.copyObj(sysUserAddVo, SysUserDo.class);
        //密码盐
        String slat = CommonUtil.randomGen(8);
        //设置默认密码123456
        String newPassword = bCryptPasswordEncoder.encode("123456" + slat);
        sysUserDo.setPassword(newPassword);
        sysUserDo.setSlat(slat);
        sysUserDo.setSource(CommonConstant.NUM_1_STR);
        sysUserDo.setStatus(CommonConstant.NUM_1_STR);
        if (StringUtils.isNotEmpty(sysUserAddVo.getRoleIds())) {
            List<String> roleIdList = Arrays.asList(sysUserAddVo.getRoleIds().split(","));
            roleIdList.forEach(roleId -> {
                sysUserRoleService.addUserRole(sysUserDo.getId(), roleId);
            });
        }
        sysUserService.save(sysUserDo);
    }

}
